/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.corespring.restaurant.web.controller;


import java.io.OutputStream;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.corespring.restaurant.model.Menu;
import org.corespring.restaurant.model.Plato;
import org.corespring.restaurant.model.Platomenu;
import org.corespring.restaurant.service.MenuManager;
import org.corespring.restaurant.service.PlatoManager;
import org.corespring.restaurant.service.ReporteManager;
import org.corespring.restaurant.service.UsuarioManager;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;





import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 * @author Aldo
 */
@Controller
public class MenuController {

    MenuManager menuManager;
    UsuarioManager usuarioManager;
    PlatoManager platoManager;
    ReporteManager reporteManager;

    @Autowired
    public MenuController(MenuManager omenuManager,UsuarioManager ousuarioManager,PlatoManager oplatoManager,ReporteManager oreporteManager){
        this.menuManager=omenuManager;
        this.usuarioManager = ousuarioManager;
        this.platoManager = oplatoManager;
        this.reporteManager = oreporteManager;
    }

    @RequestMapping("/adm_menues.htm")
    public void adm_menues(Model model, @ModelAttribute("Menu") Menu menu) {
		List<Menu> menues = menuManager.obtenerListaMenus();
                model.addAttribute("menues", menues);
                model.addAttribute("menu", menu);
    }

    @RequestMapping(value = "/adm_registroMenu.htm", method = RequestMethod.GET)
    public
    @ModelAttribute("menu")
    Menu obtenerMenu(
            @RequestParam(value = "idmenu", required = false) String idMenu, HttpServletRequest request) {
        if(idMenu ==null){
             return new Menu();
        }
        if (!(idMenu.isEmpty() || idMenu.equals(""))) {
            Menu usuario = menuManager.obtenerMenuById(idMenu);
            if (usuario == null) {
                return new Menu();
            }
            return usuario;
        }
        return new Menu();
    }

    @RequestMapping(value = "/adm_registroMenu.htm", method = RequestMethod.POST)
    public String guardarMenu(
          @RequestParam(value = "cboEstado", required = false) char estado,
          @ModelAttribute("menu") Menu menu,
            BindingResult result, SessionStatus status) {
        Date fecha = new Date();
        String hora = fecha.getHours()+":"+fecha.getMinutes()+":"+fecha.getSeconds();
        menu.setFreg(fecha);
        menu.setHreg(hora);
        menu.setEreg(estado);
        menu.setUsuario(usuarioManager.obtenerUsuarioById("admin"));
        menuManager.guardarMenu(menu);
        return "redirect:adm_menues.htm";
    }


    @RequestMapping("/eliminarMenu.htm")
    public String eliminarMenu(
            @RequestParam(value = "idMenu", required = false) String idMenu) {
        menuManager.eliminarMenu(idMenu);
        return "redirect:adm_menues.htm";
    }

    @RequestMapping("/adm_seleccionarPlato.htm")
    public void seleccionarPlato(
    @RequestParam(value = "idmenu", required = false) String idMenu,
    Model model) {
        List<Platomenu> platosmenu = platoManager.obtenerListaPlatosMenu(idMenu);
        String ids = "";
        int total = 0;
        for (Platomenu pm : platosmenu) {
             total+=1;
             if(total==1)ids = "'" + pm.getIdplato().toString()+ "'";
             else ids += ",'" + pm.getIdplato().toString()+ "'";
        }
        List<Plato> platos = platoManager.obtenerListaPlatosNoSeleccionados(ids);
        model.addAttribute("platos", platos);        
    }

   @RequestMapping(value = "/adm_listarDetallePlatos.htm", method = RequestMethod.GET)
   protected void ActualizarListaDetalle(@RequestParam(value = "idmenu", required = false) String idMenu, @RequestParam(value = "ids", required = false) String ids,
           Model model,HttpServletRequest request,
            HttpServletResponse response) throws Exception {

            if(!ids.equals("")){
                String[] array_ids = ids.split(";");
                for(int i=0; i< array_ids.length ;i++){
                    String id =array_ids[i];
                        Platomenu pm = new Platomenu();
                        pm.setIdmenu(idMenu);
                        pm.setIdplato(id);
                        menuManager.guardarPlatoMenu(pm);
                }
            }


            List<Platomenu> platosmenu = platoManager.obtenerListaPlatosMenu(idMenu);
            StringBuilder providerList = new StringBuilder();
            providerList.append("")
            .append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"gwlines arborder\">")
            .append("<tr>")
            .append("<th width=\"250\" class=\"rborder\">Plato</th>")
            .append("<th width=\"100\" class=\"rborder\">Costo</th>")
            .append("<th width=\"150\" class=\"rborder\">Tipo Plato</th>")
            .append("<th width=\"100\" class=\"rborder\">Opciones</th>")
            .append("</tr>");
            for (Platomenu pm : platosmenu) {
                 Plato plato = platoManager.obtenerPlatoById(pm.getIdplato());
                 providerList.append("<tr>")
                .append("<td class=\"rborder\">").append(plato.getNomplato()).append("</td>")
                .append("<td class=\"rborder\">").append(plato.getCosto()).append("</td>")
                .append("<td class=\"rborder\">").append(plato.getTipo().getNomtipo()).append("</td>")
                .append("<td style=\"text-align:center\"><a href=\"javascript:eliminarPlatoMenu('" + idMenu +"','"+ plato.getIdplato().toString() + "')\"><img src=\"images/imagesAdm/icon_X.png\" alt=\"picture\" width=\"13\" height=\"14\" class=\"tabpimpa\" /></a>").append("</td>")
                .append("</tr>");
            }
            providerList.append("</table>");
            //response.setContentType( "text/plain; charset=UTF-8" );
            response.getOutputStream().write( providerList.toString().getBytes());
   }

    @RequestMapping("/eliminarPlatoMenu.htm")
    protected void eliminarPlatoMenu(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "idMenu", required = false) String idMenu, @RequestParam(value = "idPlato", required = false) String idPlato)
            throws Exception{
            platoManager.eliminarPlatoMenu(idMenu,idPlato);
            List<Platomenu> platosmenu = platoManager.obtenerListaPlatosMenu(idMenu);
            StringBuilder providerList = new StringBuilder();
            providerList.append("")
            .append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"gwlines arborder\">")
            .append("<tr>")
            .append("<th width=\"250\" class=\"rborder\">Plato</th>")
            .append("<th width=\"100\" class=\"rborder\">Costo</th>")
            .append("<th width=\"150\" class=\"rborder\">Tipo Plato</th>")
            .append("<th width=\"100\" class=\"rborder\">Opciones</th>")
            .append("</tr>");
            for (Platomenu pm : platosmenu) {
                 Plato plato = platoManager.obtenerPlatoById(pm.getIdplato());
                 providerList.append("<tr>")
                .append("<td class=\"rborder\">").append(plato.getNomplato()).append("</td>")
                .append("<td class=\"rborder\">").append(plato.getCosto()).append("</td>")
                .append("<td class=\"rborder\">").append(plato.getTipo().getNomtipo()).append("</td>")
                .append("<td style=\"text-align:center\"><a href=\"javascript:eliminarPlatoMenu('" + idMenu +"','"+ plato.getIdplato().toString() + "')\"><img src=\"images/imagesAdm/icon_X.png\" alt=\"picture\" width=\"13\" height=\"14\" class=\"tabpimpa\" /></a>").append("</td>")
                .append("</tr>");
            }
            providerList.append("</table>");            
            response.getOutputStream().write( providerList.toString().getBytes());        
    }

    @RequestMapping("/exportarListaMenuReporte.htm")
    public void exportarListaMenuReporte(HttpServletResponse response) throws Exception
	{
		OutputStream out = response.getOutputStream();
		HSSFWorkbook dataWorkbook = null;

		try {
			dataWorkbook = reporteManager.obtenerListaMenuReporte();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition","attachment; filename=\""+ "MenuReporte.xls" + "\"");

		 }
		 catch (Exception e)
		 {
			System.out.println("El siguiente error ocurrio: "+e.getMessage());
		 }
		 finally
		 {
			 dataWorkbook.write(out);
			 out.close();
		 }
	}




}
